
export const generateNewHistory = async (money, level, lower) => {
    // step1 计算本次可获取资金的下限
    const lower_money = money * lower
    // step2 计算本次概率事件获得的收益
    const lottery_money = (money - lower_money) * generateRatio(level)
    // step3 计算本次最终受益
    const final_money = lower_money + lottery_money
    return parseInt(final_money)
}

const generateRatio = (level) => {
    const ratios = [0]
    let sum = 0
    let tempRatio = 1
    while (tempRatio < 10) {
        const near = Math.abs(level * 10 - tempRatio) // 0 ~ 9 , 0为最接近
        const nearRatio = 1 - near * 0.1
        const range = 100 * nearRatio * nearRatio * nearRatio * nearRatio
        sum += range
        ratios.push(sum)
        tempRatio++
    }
    const randomNum = Math.random() * ratios[ratios.length - 1]
    const ratioIndex = binarySearch(ratios, randomNum)
    const finalRatio = parseInt(Math.random() * 10) * 0.01 + ratioIndex * 0.1
    return finalRatio
}

const binarySearch = (array, key) => {
    let lowerBound = 0
    let upperBound = array.length - 1
    while (lowerBound <= upperBound) {
        const tempIndex = parseInt((lowerBound + upperBound) / 2)
        if (array[tempIndex] <= key && array[tempIndex + 1] > key) {
            return tempIndex
        } else if (lowerBound > upperBound) {
            return array.length - 1
        } else {
            if (array[tempIndex] < key) {
                lowerBound = tempIndex + 1
            } else {
                upperBound = tempIndex - 1
            }
        }
    }
    return array.length - 1
}

// 测试算法，100元在各种难度下的收益
export const test = () => {
    const money = 100
    const results = {}
    let level = 1
    while (level < 10) {
        const subResult = []
        let i = 0
        while (i < 100) {
            const tempRatio = generateRatio(level * 0.1)
            subResult.push(parseInt(money * tempRatio))
            i++
        }
        results[level] = subResult
        level += 1
    }
    // console.log("level result: ", results)
    const averages = {}
    Object.keys(results).map(key => {
        let tempSum = 0
        const tempArr = results[key]
        tempArr.map(temp => tempSum += temp)
        averages[key] = tempSum / tempArr.length
    })
    console.log("level average result: ", averages)
}